package com.ibeetl.threadpool;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.*;

public class Finder {
	static  long wsTime = 80;
	static  int max = 500;
	static Map<Integer,Long> map = new TreeMap();

	public static void main(String[] args) {

		for(int i=2;i<30;i++){
			long time = test(i);
			map.put(i,time);
		}

		map.entrySet().stream().forEach(entry -> System.out.println(entry.getKey()+":"+entry.getValue()));

	}

	public static long test(int poolSize) {

		LinkedBlockingQueue queue = new LinkedBlockingQueue();
		ThreadPoolExecutor pool =  getPool(queue);
		makeData(pool,max);
		long start = System.currentTimeMillis();
		pool.setCorePoolSize(poolSize);
		pool.setMaximumPoolSize(poolSize);
		while(!queue.isEmpty()){
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("end all "+(end-start));
		pool.shutdown();
		return  (end-start);
	}

	protected static ThreadPoolExecutor getPool(BlockingQueue queue){
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,1,1L, TimeUnit.MINUTES,queue);
		return threadPoolExecutor;
	}

	protected static void makeData(ThreadPoolExecutor pool,int size){
		for(int i=0;i<size;i++){
			pool.submit(new MyTask(i));
		}
	}

	public static class MyTask implements Runnable{

		int deep ;
		int index;
		public MyTask(int data){
			this.index = data;
			this.deep = data%20;
		}
		@Override
		public void run() {
			call();
			callWs();
//			System.out.println("end "+index);
		}

		protected  void  call(){
			if(deep==0){
				return ;
			}
			deep--;
			call();
			return ;

		}

		protected  void callWs(){
			try {
				Thread.sleep(wsTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}



}
